// components/SentimentAnalysis.js。

import React, { useState, useRef } from 'react';
import axios from 'axios';
import '../Css/SentimentAnalysis.css';
import uploadIcon from '../icon/upload.svg';
import microphoneIcon from '../icon/microphone.svg';
import clearIcon from '../icon/undo.svg';
import undoIcon from '../icon/clear.svg';

const SentimentAnalysis = () => {
  const [inputText, setInputText] = useState('');
  const [response, setResponse] = useState('');
  const inputFileRef = useRef(null);

  const handleInputChange = (event) => {
    setInputText(event.target.value);
  };

  const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
      setInputText(e.target.result);
    };
    reader.readAsText(file);
  };

  const handleSpeechInput = () => {
    setInputText('这是通过语音输入的文本内容。');
  };

  const handleClearInput = () => {
    setInputText('');
    setResponse('');
  };

  const handleUndoInput = () => {
    setInputText((prevInputText) => prevInputText.slice(0, -1));
  };

  const handlePredictClick = async () => {
    try {
      const response = await axios.post('http://localhost:5000/analyze', { text: inputText }, {
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const { response: responseText } = response.data;

      setResponse(responseText);
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <div className="container">
      <h1>用户情感分析功能页面</h1>
      <div className="text-input-container">
        <textarea
          value={inputText}
          onChange={handleInputChange}
          placeholder="请输入要分析的文本..."
        />
        <button className="icon-button upload-button" onClick={() => inputFileRef.current.click()}>
          <img src={uploadIcon} alt="Upload" />
        </button>
        <button className="icon-button microphone-button" onClick={handleSpeechInput}>
          <img src={microphoneIcon} alt="Speech" />
        </button>
        <button className="icon-button clear-button" onClick={handleClearInput}>
          <img src={clearIcon} alt="Clear" />
        </button>
        <button className="icon-button undo-button" onClick={handleUndoInput}>
          <img src={undoIcon} alt="Undo" />
        </button>
      </div>
      <button onClick={handlePredictClick}>预测情感</button>

      {response && <div className="result">{response}</div>}

      <input
        type="file"
        accept=".txt"
        ref={inputFileRef}
        style={{ display: 'none' }}
        onChange={handleFileUpload}
      />
    </div>
  );
};

export default SentimentAnalysis;
